<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category File.php
 * @Depiction:
 * Author: hwy
 * Date: 2020/3/2  17:32
 * +--------------------------------------------------------+
 */

namespace App\Models;

use Illuminate\Http\File as h_file;
use Illuminate\Database\Eloquent\Model;
// 文件
use Illuminate\Support\Facades\Storage;

class File extends Model
{

    protected $table = "file";

    protected $guarded = [
        'created_at'
    ];

    static public function getList($params)
    {
        $query = self::query();
        $perPage = empty($params['perPage']) ? 18 : $params['perPage'];

        if(!empty($params['field']) && !empty($params['order'])){
            $query = $query->orderBy($params['field'],$params['order']);
        }
        if(!empty($params['pid'])){
            $query = $query->where('name',$params['pid']);
        }

        $list = $query->paginate($perPage)->toArray();

        return return_success_msg('数据请求成功', $list);
    }


    // 添加或更新
    static public function add_update($path, $type = "admin")
    {
        // 生成file对象
        $files_data = config('filesystems.disks.' . $type);
        $file_path = $files_data['root'] . "/" . $path;
        $file_url = $files_data['url'] . "/" . $path;

        $file = File::where('file_path', $file_path)->first();
        if (empty($file)) {
            $file = new File();
            if ($h_file = new h_file($file_path)) {
                $file->file_md5 = md5_file($file_path);
                $file->file_size = $h_file->getSize();
                $file->file_name = $h_file->getFilename();
                $file->file_ext = $h_file->getExtension();
                $file->file_path = $file_path;
                $file->file_url = $file_url;
            }
        }
        $file->save();
        if($file->id){
            return $file;
        }else{
            return false;
        }

    }
}
